import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_details_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/provider/erp_info.dart';
import 'package:xiongan_app_yy/utils/ImageDetailsUtils.dart';
import 'package:xiongan_app_yy/utils/image_utils.dart';
import 'package:xiongan_app_yy/utils/toast_utils.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_card_widget.dart';
import 'package:xiongan_app_yy/widgets/comm/text_card_widget_new.dart';
import 'package:xiongan_app_yy/widgets/comm/text_exhibition_card_widget.dart';

//预约单详情展示页
class InvListItemDetailsPage extends StatefulWidget {
  final Map<String, dynamic> args;

  InvListItemDetailsPage(this.args);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _InvListItemDetailsPage();
  }
}

class _InvListItemDetailsPage extends State<InvListItemDetailsPage> {
  var _futureBuilderFuture;
  List<ImageCard> imgList = List();
  InvListDetailsEntity entity;
  dynamic reason;
  String title;
  String detailsTitle;
  String oddNumberTitle;
  String stringQR;
  String string0;
  String string1;
  String string2;
  String string3;
  String string4;
  String string5;
  String path;
  bool visibility;
  String keyName;
  String tipsName;
  String cancelText = "";
  bool cancelButtonHide = true;

  String data;

  @override
  void initState() {
    super.initState();
    if (widget.args["type"] == "入库预约单") {
      title = "入库预约详情";
      detailsTitle = "入库物资明细";
      oddNumberTitle = "货物交接单号";
      String id = widget.args["id"];
      path = "OMSWarehouseInTask/$id";
      keyName = "WarehouseInTask";
      tipsName = "司机姓名";
      if (widget.args["state"] == "未审核") {
        cancelText = "撤回预约";
        cancelButtonHide = false;
      } else if (widget.args["state"] == "审核通过") {
        cancelText = "";
        cancelButtonHide = true;
      } else if (widget.args["state"] == "审核未通过") {
        cancelText = "重新预约";
        cancelButtonHide = false;
      } else if (widget.args["state"] == "已废弃") {
        cancelText = "重新预约";
        cancelButtonHide = false;
      }
    } else if (widget.args["type"] == "出库预约单") {
      title = "出库预约详情";
      detailsTitle = "出库物资明细";
      oddNumberTitle = "领料单号";
      String id = widget.args["id"];
      path = "OMSWarehouseOutTask/$id";
      keyName = "WarehouseOutTask";
      tipsName = "司机姓名";
      if (widget.args["state"] == "未审核") {
        cancelText = "撤回预约";
        cancelButtonHide = false;
      } else if (widget.args["state"] == "审核通过") {
        cancelText = "";
        cancelButtonHide = true;
      } else if (widget.args["state"] == "审核未通过") {
        cancelText = "重新预约";
        cancelButtonHide = false;
      } else if (widget.args["state"] == "已废弃") {
        cancelText = "重新预约";
        cancelButtonHide = false;
      }
    }
    _futureBuilderFuture = getData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        title: Text(title, style: TextStyle(fontSize: 18)),
        leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
      ),
      backgroundColor: Color(0Xfff1f1f1),
      body: FutureBuilder(
        builder: _buildFuture,
        future: _futureBuilderFuture,
      ),
    );
  }

  ///snapshot就是_calculation在时间轴上执行过程的状态快照
  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return _createListView(context, snapshot);
      default:
        return null;
    }
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    data = snapshot.data.toString();
    Map<String, dynamic> dataMap = jsonDecode(data);
    if (dataMap[keyName]["flag"] == "success") {
      entity = InvListDetailsEntity.fromJson(dataMap[keyName]["datas"]);
      if (dataMap["TaskApproval"]["datas"] != null) {
        reason = dataMap["TaskApproval"]["datas"]["remark"];
      }
      Provider.of<ErpInfo>(context).setData(entity.datas);
      stringQR = entity.datas.erpno;
      string0 = entity.datas.erpno;
      string1 = entity.datas.biddingbatches;
      string2 = entity.datas.carno;
      string3 = entity.datas.driver;
      string4 = entity.datas.phone;
      string5 = entity.datas.applytime.substring(0, 10);
      if (entity.datas.imgList.length > 0) {
        if (imgList.length == 0) {
          for (int i = 0; i < entity.datas.imgList.length; i++) {
            imgList.add(ImageCard(entity.datas.imgList.elementAt(i).imgstr));
          }
          visibility = false;
        }
      } else {
        visibility = true;
      }
    } else {
      TostUtil.showToast("查询出错");
      Navigator.pop(context);
    }
    return Column(
      children: <Widget>[
        Expanded(
          child: Container(
            width: MediaQuery.of(context).size.width,
            child: Column(
              children: <Widget>[
                Container(
                  height: 180,
                  color: Colors.white,
                  padding: EdgeInsets.all(25),
                  child: Center(
                    child: GestureDetector(
                      child: QrImage(
                        data: stringQR,
                        version: QrVersions.auto,
                      ),
                      onTap: () {
                        ImageDetailsUtils.jumpImageDetails(
                            context, stringQR, true);
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: Scrollbar(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: Column(
                        children: <Widget>[
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: oddNumberTitle,
                              exhibitionText: string0),
                          TextExhibitionCardWidget(
                              distance: EdgeInsets.only(
                                  right: 15, left: 15, bottom: 16, top: 16),
                              title: "预约时间",
                              exhibitionText: string5 ?? ""),
                          TextCardWidget(
                            margin: EdgeInsets.only(top: 10, bottom: 10),
                            onPressed: () {
                              //Navigator.pushNamed(context, "/storageDetails",arguments: detailsBean);
                              Navigator.pushNamed(context, "/storageDetails",
                                  arguments: {
                                    "type": "pull",
                                    "title": detailsTitle
                                  });
                            },
                            title: "物资明细",
                          ),
                          Offstage(
                              offstage:
                                  dataMap["TaskApproval"]["datas"] == null,
                              child: TextExhibitionCardWidget(
                                  distance: EdgeInsets.only(
                                      right: 15, left: 15, bottom: 16, top: 16),
                                  title: "原因",
                                  border: Border(
                                      bottom: BorderSide(
                                          width: 1, color: Color(0xffdddddd))),
                                  exhibitionText: reason ?? "无")),
                          TextExhibitionCardWidget(
                              title: "供应商:",
                              exhibitionText: entity.datas == null
                                  ? ""
                                  : entity.datas.supplyname,
                              distance: EdgeInsets.only(
                                  left: 16, right: 16, bottom: 15, top: 15),
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          TextExhibitionCardWidget(
                              title: "工程编号:",
                              exhibitionText: entity.datas == null
                                  ? ""
                                  : entity.datas.projectno,
                              distance: EdgeInsets.only(
                                  left: 16, right: 16, bottom: 15, top: 15),
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          TextExhibitionCardWidget(
                              title: "工程名称:",
                              exhibitionText: entity.datas == null
                                  ? ""
                                  : entity.datas.projectname,
                              distance: EdgeInsets.only(
                                  left: 16, right: 16, bottom: 15, top: 15),
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          TextExhibitionCardWidget(
                              title: "确定交货日期:",
                              exhibitionText: "",
                              distance: EdgeInsets.only(
                                  left: 16, right: 16, bottom: 15, top: 15),
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          TextCardWidgetNew(
                              onPressed: () {
                                //Navigator.pushNamed(context, "/storageDetails",arguments: detailsBean);
                                Navigator.pushNamed(context, "/carDetails",
                                    arguments: {"datas": entity.datas.carList});
                              },
                              title: "车辆信息:",
                              textNum: false,
                              details: false,
                              num: "${entity.datas.carList.length}辆",
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          TextExhibitionCardWidget(
                              title: "停靠月台:",
                              exhibitionText: "",
                              distance: EdgeInsets.only(
                                  left: 16, right: 16, bottom: 15, top: 15),
                              border: Border(
                                  bottom: BorderSide(
                                      width: 1, color: Color(0xffefefef)))),
                          Offstage(
                            offstage: visibility,
                            child: Container(
                              height: 86,
                              width: double.infinity,
                              margin: EdgeInsets.only(bottom: 8),
                              decoration: BoxDecoration(color: Colors.white),
                              child: Scrollbar(
                                  child: SingleChildScrollView(
                                scrollDirection: Axis.horizontal,
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: imgList,
                                ),
                              )),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                Offstage(
                    offstage: cancelButtonHide,
                    child: Container(
                      width: double.infinity,
                      height: 48,
                      child: FlatButton(
                        color: Color(0XFF00A5F1),
                        child: Text(
                          cancelText,
                          style: TextStyle(color: Colors.white),
                        ),
                        onPressed: _cancel,
                      ),
                    ))
              ],
            ),
          ),
        )
      ],
    );
  }

  Future getData() async {
    var response = InternetAPI.getInstance().dio.get(
          path,
        );
    return response;
  }

  void _cancel() {
    if (cancelText == "重新预约") {
      if (widget.args["type"] == "入库预约单") {
        /* InternetAPI.getInstance()
            .get("OMS/MiWarehouseInTask/DeleteMiWarehouseInTask", (data) {
          if (data == true) {

          }
        }, params: {
          'id': entity.datas.id,
          'operaterUserId': DataSingleton().Data.id,
          'operaterUserName': DataSingleton().Data.username,
          'tenantId': DataSingleton().Data.tenantId,
        });*/
        Navigator.pushNamed(context, "/invListNew", arguments: {"bean": entity})
            .then((value) {
          if (value == "ok") {
            Navigator.pop(context, "ok");
          }
        });
      } else if (widget.args["type"] == "出库预约单") {
        /*InternetAPI.getInstance()
            .get("OMS/MiWarehouseOutTask/DeleteMiWarehouseOutTask", (data) {
          if (data == true) {

          }
        }, params: {
          'id': entity.datas.id,
          'operaterUserId': DataSingleton().Data.id,
          'operaterUserName': DataSingleton().Data.username,
          'tenantId': DataSingleton().Data.tenantId,
        });*/
        Navigator.pushNamed(context, "/outvListNew",
            arguments: {"bean": entity}).then((value) {
          if (value == "ok") {
            Navigator.pop(context, "ok");
          }
        });
      }
    } else if (cancelText == "撤回预约") {
      InternetAPI.getInstance()
          .get("OMS/MiWarehouseInTask/DeleteMiWarehouseInTask", (data) {
        if (data == true) {
          TostUtil.showToast("撤回成功");
          Navigator.pop(context, "ok");
        }
      }, params: {
        'id': entity.datas.id,
        'operaterUserId': DataSingleton().Data.id,
        'operaterUserName': DataSingleton().Data.username,
        'tenantId': DataSingleton().Data.tenantId,
      });
    }
  }
}

class ImageCard extends StatefulWidget {
  final String asetImg;

  ImageCard(this.asetImg) : assert(asetImg != null);

  @override
  State<StatefulWidget> createState() {
    return ImageCardState();
  }
}

class ImageCardState extends State<ImageCard> {
  String image = "";

  @override
  void initState() {
    ImageDownloadUtil.getImageBase64(widget.asetImg, (data) {
      setState(() {
        image = data;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
        margin: EdgeInsets.all(6),
        child: GestureDetector(
          child: ImageDownloadUtil.isImageType(image),
          onTap: () {
            ImageDetailsUtils.jumpImageDetails(context, image, false);
          },
        ));
  }
}
